/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : my_profile.js                            
*  Description  : 프로필 관리
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-06-27  김효순    Created.  
*******************************************************************************/

jQuery(function($){
	// 연령대
	function clsAge()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsAge.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile tbody tr:eq(0)");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setList: function(thisData){
			this.listData = [{
				"나이코드": ""
				, "내용": "-- 연령대선택 --"
			}].concat(thisData);
			
			this.display();
		}
		, display: function(){
			var $layer = this.$getLayer();
			var thisClass = this;
			
			$layer.find("select").empty();
			for(var i=0;i<this.listData.length;i++){
				$layer.find("select").append("<option />");
			}
			$layer.find("option").each(function(n){
				$(this).text(thisClass.listData[n]["내용"]);
			});
		}
		, getKey: function(n){
			return this.listData[n]["나이코드"];
		}
		, getValue: function(){
			var $layer = this.$getLayer();
			var n = $layer.find("option").index($layer.find("option:selected"));
			
			return this.getKey(n);
		}
		, setValue: function(val){
			var $layer = this.$getLayer();
			
			for(var i=0;i<this.listData.length;i++){
				if(this.getKey(i) == val) break;
			}
			
			if(i<this.listData.length){
				$layer.find("option").eq(i).attr("selected", "selected");
			}
		}
		, isLoaded: function(){
			if(this.listData) return true;
			else return false;
		}
	}
	
	// 지역
	function clsArea()
	{
		this._HTMLDom = null;
		this.listData = null;
		
		this._init();
	}
	
	clsArea.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile tbody tr:eq(1)");
			this._HTMLDom = {
				"$layer": $layer
			}
		}
		, $getLayer: clsAge.prototype.$getLayer
		, setList: function(thisData){
			this.listData = [{
				"지역코드": ""
				, "내용": "-- 지역선택 --"
			}].concat(thisData);
			
			this.display();
		}
		, display: clsAge.prototype.display
		, getKey: function(n){
			return this.listData[n]["지역코드"];
		}
		, getValue: clsAge.prototype.getValue
		, setValue: clsAge.prototype.setValue
		, isLoaded: clsAge.prototype.isLoaded
	}
	
	// 직업
	function clsJob()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsJob.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile tbody tr:eq(2)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").attr("placeholder", "직업을 입력해 주세요.");
		}
		, $getLayer: clsAge.prototype.$getLayer
		, getValue: function(){
			return this._HTMLDom["$layer"].find("input:text").val();
		}
		, setValue: function(val){
			this._HTMLDom["$layer"].find("input:text").val(val);
		}
	}
	
	
	// 핸디
	function clsHandi()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsHandi.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile tbody tr:eq(3)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").attr("placeholder", "입력");
		}
		, $getLayer: clsAge.prototype.$getLayer
		, getValue: clsJob.prototype.getValue
		, setValue: clsJob.prototype.setValue
	}
	
	
	
	// 평균타수
	function clsAvg()
	{
		this._HTMLDom = null;
		
		this._init();
	}
	
	clsAvg.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile tbody tr:eq(4)");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").attr("placeholder", "평균타수를 입력해 주세요.");
		}
		, $getLayer: clsAge.prototype.$getLayer
		, getValue: clsJob.prototype.getValue
		, setValue: clsJob.prototype.setValue
	}
	
	// 프로파일 이미지
	function clsProfileImage()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsProfileImage.prototype = {
		_init: function(){
			var $layer = $("div#container section#my_profile div.photo");
			var thisClass = this;
			
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("img[alt='사진']").width(135).height(135);/*.error(function(){
				var img = _gf.getDefaultProfileImage(thisClass.infoData["성별코드"]);
				$(this).attr("src", img);
			});*/
			
			this.setInfo({});
		}
		, $getLayer: clsAge.prototype.$getLayer
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display();
		}
		, setFacebook: function(img){
			this.infoData["파일명"] = img;
			this.infoData["원본파일명"] = "";
			this.display();
		}
		, display: function(){
			var $layer = this._HTMLDom["$layer"];
			var thisClass = this;
			
			$layer.find("img[alt='사진']").attr("src", _gf.filePath2Url(this.infoData["파일명"])).unbind("error").error(function(){
				var img = _gf.getDefaultProfileImage();
				$(this).attr("src", img);
			});
		}
		, getInfo: function(){
			return this.infoData;
		}
	}
	
	
	// 서버통신
	function clsComm()
	{
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){
			
		}
		, getProfile: function(){
			var thisClass = this;
			
			//ajax
			var serviceName = "getMyProfile";
			var options = {
				
			}
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
					, "결과값": {}
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					
					res["결과값"] = {
						"파일코드": _util.nvl(obj["fileSeq"]).trim()
					}
				}
				
				document.objControl.finishProfile(res);
			});
		}
		// 페이스북 사진 저장
		, facebookPhotoSubmit: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "updateMyProfilePhoto";
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				"fileSeq": arg["파일코드"]
				, "orgnFileName": ""
				, "saveFileName": arg["파일명"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
		// 프로필 저장
		, profileSubmit: function(arg){
			var thisClass = this;
			
			arg["콜백"] = arg["콜백"] || document.objControl.finishProfileSubmit;
			
			//ajax
			var serviceName = "updateMyProfile";
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				"age": arg["나이코드"]
				, "region": arg["지역코드"]
				, "job": arg["직업"]
				, "handi": arg["핸디"]
				, "average": arg["평균타수"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
		// 페이스북 아이디 저장
		, facebookSaveId: function(arg){
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			//ajax
			var serviceName = "registFacebookId";
			_gf.ajax({
				"sid": "US001"
				, "servicename": serviceName
			}, {
				"facebookId": arg["아이디"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": _gf.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
	}
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objAge = null;
		this.objArea = null;
		this.objJob = null;
		this.objHandi = null;
		this.objAvg = null;
		this.objProfileImage = null;
		
		this._permitStart = null;
		
		this.ageCodeList = null;
		this.areaCodeList = null;
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objAge = new clsAge();
			this.objArea = new clsArea();
			this.objJob = new clsJob();
			this.objHandi = new clsHandi();
			this.objAvg = new clsAvg();
			this.objProfileImage = new clsProfileImage();
			
			this._beforeStart();
			this._bind();
		}
		, _preload: function(){
			_gf.spinStart();
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			$.ajax({
				url: _ROOT + "/js/mypage_common.js"
				, dataType: "script"
				, async: false
				, success: function(){
					
				}
				, error: function(){
					alert("error");
				}
			});
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return (_gf.getMyInfoData() && _gf.getAreaCodeData() && _gf.getAgeCodeData());
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _bind: function(){
			var thisClass = this;
			
			// 사진등록
			this.objProfileImage.$getLayer().on("click", "img[alt='사진등록'], img[alt='페이스북 연동'], img[alt='개인정보변경']", function(){
				var alt = $(this).attr("alt");
				
				switch(alt){
					case "사진등록":
						var winProfileImageRegist = window.open(_ROOT + "/popup/pop_profile.html", "winProfileImageRegist", "width=500, height=300, scrollbars=0");
						if(winProfileImageRegist) winProfileImageRegist.focus();
						break;
					case "페이스북 연동":
						thisClass.getFacebookProfile();
						break;
					case "개인정보변경":
					
				}
			});
			
			// 수정
			$("img[alt='수정']").click(function(){
				_gf.spinStart();
				var pi = thisClass.objProfileImage.getInfo();
				
				if(!pi["원본파일명"] && pi["파일명"]){
					thisClass.objComm.facebookPhotoSubmit({
						"파일코드": pi["파일코드"]
						, "파일명": pi["파일명"]
						, "콜백": function(ret){
							thisClass.finishFacebookPhotoSubmit(ret);
						}
					});
				}else{
					thisClass.objComm.profileSubmit({
						"나이코드": thisClass.objAge.getValue()
						, "지역코드": thisClass.objArea.getValue()
						, "직업": thisClass.objJob.getValue()
						, "핸디": thisClass.objHandi.getValue()
						, "평균타수": thisClass.objAvg.getValue()
					});
				}
			});
			
			// 취소
			$("img[alt='취소']").click(function(){
				thisClass._start();
			});
			
			// 평균타수 수정
			this.objHandi.$getLayer().on("change", "input:text", function(){
				var nv = parseInt(thisClass.objHandi.getValue());
				
				if(!isNaN(nv)){
					thisClass.objAvg.setValue(nv+72);
				}
			});
		}
		, _start: function(){
			var myInfo = _gf.getMyInfoData();
			var thisClass = this;
			
			// 프로필
			this.objComm.getProfile();
			
			this.objAge.setList(_gf.getAgeCodeData());
			this.objArea.setList(_gf.getAreaCodeData());
			
			this.objAge.setValue(myInfo["나이코드"]);
			this.objArea.setValue(myInfo["지역코드"]);
			this.objJob.setValue(myInfo["직업"]);
			this.objHandi.setValue(myInfo["핸디"]);
			this.objAvg.setValue(myInfo["평균타수"]);
			
			_util.executeThread(function(){
				return _facebook_status;
			}, function(){
				if(_facebook_status["상태"] == "connected"){
					thisClass.objComm.facebookSaveId({
						"아이디": _facebook_status["아이디"]
					});
				}
			});
		}
		// 프로파일 이미지 정보
		, getProfileImageData: function(){
			return this.objProfileImage.getInfo();
		}
		, getGenderCode: function(){
			var myInfo = _gf.getMyInfoData();
			
			return myInfo["성별코드"];
		}
		// 페이스북 프로파일 이미지 받아오기
		, getFacebookProfile: function(){
			var thisClass = this;
			
			if(document.domain == "192.168.0.82"){
				thisClass.setFBProfileImage("https://graph.facebook.com/100002241124947/picture?type=large");
				return;
			}
			
			switch(_facebook_status["상태"]){
				case "connected":
					_util.executeThread(function(){
						return _facebook_status["me"];
					}, function(){
						thisClass.setFBProfileImage(_facebook_status["me"]["이미지"]);
					});
					break;
				case "not_authorized":
					$(document).one("FBME", function(){
						thisClass.setFBProfileImage(_facebook_status["me"]["이미지"]);
					});
				default:
					FB.login(function(response) {
						$(document).one("FBME", function(){
							thisClass.setFBProfileImage(_facebook_status["me"]["이미지"]);
						});
						updateStatus(response);
						//alert(thisClass.getFacebookProfile);
						//thisClass.getFacebookProfile();
					});
					break;
			}
		}
		// 프로파일 완료
		, finishProfile: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			var myInfo = _gf.getMyInfoData();
			
			this.objProfileImage.setInfo({
				"파일코드": ret["결과값"]["파일코드"]
				, "파일명": myInfo["이미지"]
				, "원본파일명": myInfo["원본파일명"]
				, "성별코드": this.getGenderCode()
			});
		}
		// 프로파일 사진 설정 완료
		, closeProfileImage: function(w){
			var thisClass = this;
			if(w) w.close();
			
			_gf.getMyInfo({
				"콜백": function(){
					var myInfo = _gf.getMyInfoData();
					document.objMypageControl.setProfileImage(myInfo["이미지"]);
					thisClass.objComm.getProfile();
				}
			});
		}
		// 수정완료
		, finishProfileSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			document.location.reload();
		}
		// FB프로파일 완료
		, setFBProfileImage: function(val){
			this.objProfileImage.setFacebook(val + "");
		}
		// 페이스북 사진 저장 완료
		, finishFacebookPhotoSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			
//			this.objComm.profileSubmit({
//				"나이코드": this.objAge.getValue()
//				, "지역코드": this.objArea.getValue()
//				, "직업": this.objJob.getValue()
//				, "핸디": this.objHandi.getValue()
//				, "평균타수": this.objAvg.getValue()
//			});
		}
	}
	
	document.objControl = new clsControl();
	document.objControl._init();
});
